'''
主控中心，统一管理token，设置初始化菜单，设置行业等操作
'''
import requests
import json
import datetime
try:
    from .urls import gtokenUrl, createMenuURL, setIndustry, getJsTicket
    from .data import info, menu
except:
    from app.envs.urls import gtokenUrl, createMenuURL, setIndustry, getJsTicket
    from app.envs.data import info, menu
import logging
from app.envs.token_auth import WXToken
logger = logging.getLogger('info')



class MControl:
    __instance = None

    def __new__(cls, name):
        if cls.__instance == None:
            cls.__instance = object.__new__(cls)
            return cls.__instance
        else:
            #return 上一次创建的对象的引用
            return cls.__instance

    def __init__(self, name):
        self.name = name 
        # 获取token及本次token获取的时间
        logger.info('mcu __init__ 0')
        #self.__tokenTime, self.__token, self.__JsTicket = self.getToken()
       
        # 首次初始化时设置菜单
        self.init_menu()
        logger.info('mcu __init__ 2')
        # 设置行业
        #self.init_industry()

    @staticmethod
    def getToken():
        # 获取token的同时获取js_ticket,因为二者时间上同步
        url = gtokenUrl.format(**info)
        response = requests.get(url, verify=False)
        print(url)
        print(response.text)
        token = json.loads(response.text)['access_token']
        # 获取js_ticket
        getJsurl = getJsTicket.format(**{'token':token})
        tmp = requests.get(getJsurl, verify=False)
        tresult = json.loads(tmp.text)
        if tresult.get('errcode') == 0:
            js_ticket = tresult.get('ticket')
        else:
            logger.info('获取js_ticket失败')
        #
        getTime = datetime.datetime.now()

        logger.info('在时间 ：{0} 获取token ：{1}，jsTicket：{2}， 7200s后失效'.format(str(getTime), token, tresult.get('ticket')))
        return datetime.datetime.now(), token, js_ticket

    def getJsTicket(self):
        #return self.__JsTicket
        wxtoken = WXToken()
        return wxtoken.getJsTicket('niuneng')

    def get_token(self):
        #return self.__token
        wxtoken = WXToken()
        return wxtoken.getToken('niuneng')
        
        '''

        logger.info('this interface is error')
        return None, None, None
        '''

    '''
    def getJsTicket(self):
        # jsTicket同步获取，同步失效
        #TODO
        from socket_internal.querydb import get_token
        appname = 'AlarmServer'
        ret = get_token(appname)
        if ret[0] != 0:
            return None
        
        ret_json = json.loads(ret[1])
        tokeninfo = ret_json.get('tokenInfo')
        if tokeninfo is not None:
            return tokeninfo.get('jsticket')
        else:
            return None
    
    
    # 正式环境采用该接口
    def get_token(self):
        #首先判断本次token的获取时间与现在的时间间隔，大于2sh时重新获取token
        # TODO
        from socket_internal.querydb import get_token
        appname = 'niuneng'
        ret = get_token(appname)
        if ret[0] != 0:
            return None
        
        ret_json = json.loads(ret[1])
        tokeninfo = ret_json.get('tokenInfo')
        if tokeninfo is not None:
            return tokeninfo.get('token')
        else:
            return None
    '''

    def init_menu(self):
        tmenu = json.dumps(menu, ensure_ascii = False).encode('utf-8')
        # 设置token项
        #tmp = {'token': self.getToken()[1]}
        tmp = {'token': self.get_token()}
        response = requests.post(createMenuURL.format(**tmp), data = tmenu)
        result = json.loads(response.text)
        if result['errcode'] == 0:
            print('创建菜单成功！！！')
        else:
            print('创建菜单失败！！！')

    def init_industry(self):
        # 设置行业
        from config.data import indutry
        tmp = {'token': self.get_token()}
        response = requests.post(setIndustry.format(**tmp), data = indutry)
        print(response)

    def update_token(self):
        logger.info('update token 0')
        self.__tokenTime, self.__token, self.__JsTicket = self.getToken()
        logger.info('update toekn 1')





